<script>
//存储桶名称: lxinyu-1234-1328094609
//地域： ap-beijing
//SecretId:AKIDX3mqohYCl9KGDdx8CFNXfp8WzOzQtHco
//SecretKey:8A94paJ2vvyDRi1AJLSynL1kORrliR7o
import COS from 'cos-js-sdk-v5';
import { Message } from 'element-ui';
export default {
    props: {
        value: {
            type: String,
            default: ''
        }
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
       
        const isJPG =  ['image/jpeg', 'image/jpg', 'image/png', 'image/gif' , 'image/BMP'].includes(file.type) //文件上传格式
        const isLt2M = file.size / 1024 / 1024 < 10; //文件上传大小

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG, JPEG, PNG, GIF, BMP 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10  MB!');
        }
        return isJPG && isLt2M;
      },
    //   1、npm i cos-js-sdk-v5 装包 引包
      uploadImage(params) {
        // console.log(params);
        // 2、cos初始化 传入SecretId，SecretKey
        const cos = new COS({
            SecretId: 'AKIDX3mqohYCl9KGDdx8CFNXfp8WzOzQtHco',
            SecretKey: '8A94paJ2vvyDRi1AJLSynL1kORrliR7o'
        })
        cos.putObject({
            Bucket: 'lxinyu-1234-1328094609', //名称
            Region: 'ap-beijing', //地域
            Key: params.file.name, //文件名称
            StorageClass: 'STANDARD' ,//固定值
            Body: params.file, //文件对象
        },(err, data) => {
            if(data.statusCode === 200 && data.Location){
               this.$emit('input', `https://${data.Location}`)
            }else{ 
                Message({type: 'error,', message: err.message})
            }
        })
      }
    }
  }
</script>
<template>
    <div class="upload">
        <el-upload
        class="avatar-uploader"
        action=""
        :http-request="uploadImage"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="value" :src="value" class="avatar" style="border-radius: 6px;">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
     </el-upload>
    </div>
</template>
<style scoped>

.avatar-uploader-icon{
    border: 1px dashed #d9d9d9 !important;
}
.avatar-uploader-icon {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
  }
  .avatar-uploader-icon:hover {
    border-color: #409EFF !important;
  }

  .avatar-uploader-icon {
    overflow: hidden;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>